package com.sf.iisp.scheduler.task;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Date;

/**
 * Created by qi on 16-7-6.
 */
public class ReserveUnbindingTask implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReserveUnbindingTask.class);

    private RedisTemplate<String, Object> redisTemplate;
    private String keyPrefix;
    private String topic;

    public ReserveUnbindingTask(RedisTemplate redisTemplate, String keyPrefix, String topic) {
        this.redisTemplate = redisTemplate;
        this.keyPrefix = keyPrefix;
        this.topic = topic;
    }

    @Override
    public void run() {
        //TODO: 查询Redis预约到期的，然后发送消息unbinding-201607161533
        String currentDate = DateFormatUtils.format(new Date(), "yyyyMMddHHmm");
        LOGGER.debug("current time = {}", currentDate);

        Boolean existsKey = redisTemplate.hasKey(keyPrefix + currentDate);
        //BindingRecord records = ( BindingRecord) listOps.index(keyPrefix + currentDate, 0);
        LOGGER.info("unbinding records is null?   {}", existsKey);

        if (existsKey) {
            LOGGER.info("send topic = {}, message = {}", topic, keyPrefix + currentDate);
            redisTemplate.convertAndSend(topic, keyPrefix + currentDate);
        }

        LOGGER.debug("no record is unbound. key = {}", keyPrefix + currentDate);
        //redisTemplate.convertAndSend("usr:unbinding","unbinding");
    }
}
